<?php
/**
* phpmailer发送邮件 
* 发送网易邮箱126.com
* 
*/
require_once (LIB . DS . 'PHPMailer_5.2.4/class.phpmailer.php');
class SendMailUtil {
	public static function getDB() {
		global $CONFIG;
		$dbutil = new DbUtil ( $CONFIG ['DB'] ['db_host'], $CONFIG ['DB'] ['db_user'], $CONFIG ['DB'] ['db_password'], $CONFIG ['DB'] ['db_database'] );
		return $dbutil;
	}
	
	/**
	 *
	 *
	 * 发送email常用类
	 * 
	 * @param string $messagetitle
	 *        	发送邮件标题
	 * @param string $messagebody
	 *        	发送邮件body,支持html
	 * @param string $adress
	 *        	收件人
	 */
	public static function sendmail($messagetitle, $messagebody, $adress) {
		self::resetCurDayMail ();
		$sender = self::loadSendMaler ();
		
		// echo $messagebody;
		$mail = new PHPMailer ();
		
		// 采用SMTP发送邮件
		$mail->IsSMTP ();
		
		// 邮件服务器
		$mail->Host = $sender->smtp;
		// $mail->Host = "smtp.qq.com";
		$mail->SMTPDebug = 0;
		
		// 使用SMPT验证
		$mail->SMTPAuth = true;
		
		// SMTP验证的用户名称
		$mail->Username = $sender->name;
		// $sender->password
		// SMTP验证的秘密
		$mail->Password = $sender->password;
		
		$mail->Port =  $sender->port;
		// 设置编码格式
		$mail->CharSet = "utf-8";
		
		// 设置主题
		$mail->Subject = $messagetitle;
		
		// $mail->AltBody = "register success"";
		
		// 设置发送者
		$mail->SetFrom ( $sender->name, $sender->sitename );
		$mail->FromName = $sender->sitename; // 发件人
		$mail->From = $sender->name; // 发件人邮箱
		                             // 采用html格式发送邮件
		$mail->MsgHTML ( $messagebody );
		// $mail->AddReplyTo($mail_msg->name, $mail_msg->desc);
		// 接受者邮件名称
		$mail->AddAddress ( $adress, $sender->sitename ); // 发送邮件
		if (! $mail->Send ()) {
			return "Mailer Error: " . $mail->ErrorInfo;
		} else {
			self::updateDayMail ( $sender->id );
			return "Success";
		}
	}
	
	/**
	 * 加载发送用户者
	 * 
	 * @return string
	 */
	public function resetCurDayMail() {
		require_once SERVICE . DS . 'SendMailService.class.php';
		$mailservice = new SendMailService ( self::getDB () );
		$mailservice->resetCurDayMail ();
	}
	/**
	 * 更新当前邮件当天发送记录
	 * 
	 * @return string
	 */
	public function updateDayMail($mid) {
		require_once SERVICE . DS . 'SendMailService.class.php';
		$mailservice = new SendMailService ( self::getDB () );
		$mailservice->updateMailCount ( $mid );
	}
	/**
	 * 加载发送用户者
	 * 
	 * @return string
	 */
	public function loadSendMaler() {
		require_once SERVICE . DS . 'SendMailService.class.php';
		$mailservice = new SendMailService ( self::getDB () );
		$mailers = $mailservice->getSendMails ();
		foreach ( $mailers as $mailer ) {
			// echo("mailer::".$mailer->count_use.$mailer->conut_total."////////");
			if ($mailer->count_use < $mailer->count_total) {
				return $mailer;
			}
		}
		return $mailers [rand ( 0, count ( $mailers ) )];
	}
}
?>